package deadlock;

import java.io.FileOutputStream;

/**
 * @author Brook
 */
public class DiningPhilosophers {



    public static class Philosopher implements Runnable {

        private Object lestChopstick;
        private Object rightChopstick;

        public Philosopher(Object lestChopstick, Object rightChopstick) {
            this.lestChopstick = lestChopstick;
            this.rightChopstick = rightChopstick;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    doAction("Thinking");
                    synchronized (lestChopstick) {
                        doAction("Picked up Left chopstick");
                        synchronized (rightChopstick) {
                            doAction("Picked up Right chopstick--->eating");
                            doAction("Put down Right chopstick");
                        }
                        doAction("Put down Left chopstick");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void doAction(String action) throws InterruptedException {
            System.out.println(Thread.currentThread().getName() + "" + action);
            Thread.sleep((long) (Math.random() * 100));
        }
    }

    public static void main(String[] args) {
        Philosopher[] philosophers = new Philosopher[5];
        Object[] chopsticks = new Object[philosophers.length];
        for (int i = 0; i < chopsticks.length; i++) {
            chopsticks[i] = new Object();
        }

        for (int i = 0; i < philosophers.length; i++) {
            Object leftChopstick = chopsticks[i];
            Object rightChopstick = chopsticks[(i+1)%chopsticks.length];

            //解决问题
            if(i == philosophers.length -1) {
                philosophers[i] = new Philosopher(rightChopstick, leftChopstick);
            }else {
                philosophers[i] = new Philosopher(leftChopstick, rightChopstick);
            }
            new Thread(philosophers[i], "哲学家" + (i+1) + "号").start();
        }
    }

}
